import 'package:dio/dio.dart';
import 'package:shop/base/log/log_manager.dart';

class JMNetLogInterceptors extends Interceptor {
  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    var isLog = response.requestOptions.extra['log'];
    // 没有开启日志打印
    if (isLog == null || isLog == false) return handler.next(response);

    // 开启日志打印
    var baseUrl = response.requestOptions.baseUrl;
    var path = response.requestOptions.path;
    var method = response.requestOptions.method;
    LogManager().log('$baseUrl$path [$method]');

    var header = response.requestOptions.headers;
    LogManager().log(header);

    if (method.toUpperCase() == 'GET') {
      var data = response.requestOptions.queryParameters;
      LogManager().log(data);
    } else {
      var data = response.requestOptions.data?.fields ?? {};
      LogManager().log(data);
    }

    LogManager().log(response.data);
    handler.next(response);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    var isLog = err.requestOptions.extra['log'];
    // 没有开启日志打印
    if (isLog == null || isLog == false) return handler.next(err);

    // 开启日志打印
    var baseUrl = err.requestOptions.baseUrl;
    var path = err.requestOptions.path;
    var method = err.requestOptions.method;
    LogManager().log('$baseUrl$path [$method]',type: LogType.error);

    var header = err.requestOptions.headers;
    LogManager().log(header,type: LogType.error);

    if (method.toUpperCase() == 'GET') {
      var data = err.requestOptions.queryParameters;
      LogManager().log(data);
    } else {
      var data = err.requestOptions.data?.fields ?? {};
      LogManager().log(data.toString());
    }

    LogManager().log(err);
    handler.next(err);
  }
}
